/*
 * Copyright (C) 2007-2008  Alessandro Melandri
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * */

package net.melandri.jtextfileparser.utils;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

/**
 * @author Alessandro Melandri
 * @version 1.0
 * 
 * Class containing utility methods for managing Strings
 * */
public class StringUtils{

	
	/**
	 * Sustitutes a string portion with another string. 
	 * It's useful for substituting one or more chars in a string
	 * 
	 * With jdk 1.5 or greater this method may be replaced by the String method 
	 * public String replace(CharSequence target,CharSequence replacement)
	 * 
	 * @param str	 Orginal string
	 * @param chars	 TreeMap containg couples: old chars sequence - new chars sequence
	 * 
	 * @return 	 Returns the modified string
	 * */
	public static String substituteChars(String originalString, TreeMap chars){
		
		String parsedString = originalString;
		
		Set originalChars = chars.keySet();
		Iterator it = originalChars.iterator();
		
		while (it.hasNext()){
		
			String originalChar = (String)it.next();
			String newChar = (String) chars.get(originalChar);
			
			int pos = parsedString.indexOf(originalChar);
			int posHelper = 0;
			int originalCharLength = originalChar.length();
			
			while (pos != -1){

				String before = parsedString.substring(0, pos);

				String after = "";
				if (posHelper < parsedString.length())
					after  = parsedString.substring(pos + originalCharLength,parsedString.length());
					
				parsedString = before + newChar + after;
				posHelper = pos+1;
				pos = parsedString.indexOf(originalChar,posHelper);
			}
		}
		
		return parsedString;
	}

}
